<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DBC上传调试</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
        .container { max-width: 800px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; }
        .upload-area { border: 2px dashed #ccc; padding: 30px; text-align: center; margin: 20px 0; }
        .upload-area.drag-over { border-color: #007bff; background: #f0f8ff; }
        button { padding: 10px 20px; margin: 5px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
        button:hover { background: #0056b3; }
        .result { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 4px; }
        .success { background: #d4edda; border-color: #c3e6cb; color: #155724; }
        .error { background: #f8d7da; border-color: #f5c6cb; color: #721c24; }
        .log { background: #f8f9fa; border: 1px solid #e9ecef; padding: 10px; margin: 10px 0; font-family: monospace; max-height: 200px; overflow-y: auto; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔧 DBC文件上传调试</h1>
        
        <div class="upload-area" id="uploadArea">
            <p>📁 拖拽DBC文件到这里，或点击下面的按钮选择文件</p>
            <input type="file" id="dbcFile" accept=".dbc" style="display: none;">
            <button onclick="document.getElementById('dbcFile').click()">选择DBC文件</button>
        </div>

        <div class="result" style="display: none;" id="result"></div>
        
        <h3>📝 调试日志</h3>
        <div class="log" id="debugLog"></div>
        
        <button onclick="clearLog()">清除日志</button>
        <button onclick="testSampleData()">测试示例数据</button>
    </div>

    <script>
        // 简单的日志系统
        const originalConsole = {
            log: console.log,
            error: console.error,
            warn: console.warn
        };

        function addToLog(type, message) {
            const log = document.getElementById('debugLog');
            const timestamp = new Date().toLocaleTimeString();
            log.innerHTML += `<div>[${timestamp}] ${type}: ${message}</div>`;
            log.scrollTop = log.scrollHeight;
        }

        console.log = function(...args) {
            originalConsole.log.apply(console, args);
            addToLog('LOG', args.join(' '));
        };

        console.error = function(...args) {
            originalConsole.error.apply(console, args);
            addToLog('ERROR', args.join(' '));
        };

        console.warn = function(...args) {
            originalConsole.warn.apply(console, args);
            addToLog('WARN', args.join(' '));
        };

        function clearLog() {
            document.getElementById('debugLog').innerHTML = '';
        }

        function showResult(message, isError = false) {
            const result = document.getElementById('result');
            result.className = 'result ' + (isError ? 'error' : 'success');
            result.innerHTML = message;
            result.style.display = 'block';
        }

        // 测试示例数据
        function testSampleData() {
            console.log('测试示例数据加载...');
            try {
                if (typeof DBCEditor !== 'undefined') {
                    const editor = new DBCEditor();
                    const stats = editor.database.getStatistics();
                    showResult(`✅ 示例数据加载成功！<br>帧数: ${stats.frameCount}, 信号数: ${stats.signalCount}, 节点数: ${stats.nodeCount}`);
                } else {
                    showResult('❌ DBCEditor类未定义，请检查script.js是否正确加载', true);
                }
            } catch (error) {
                console.error('示例数据测试失败:', error);
                showResult('❌ 示例数据测试失败: ' + error.message, true);
            }
        }

        // 文件上传测试
        document.getElementById('dbcFile').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (!file) return;

            console.log(`开始测试文件上传: ${file.name} (${file.size} 字节)`);
            
            try {
                // 检查类是否存在
                if (typeof DBCTokenizer === 'undefined') {
                    throw new Error('DBCTokenizer类未定义');
                }
                if (typeof DBCParser === 'undefined') {
                    throw new Error('DBCParser类未定义');
                }
                if (typeof CANDatabase === 'undefined') {
                    throw new Error('CANDatabase类未定义');
                }

                const reader = new FileReader();
                reader.onload = function(e) {
                    try {
                        const content = e.target.result;
                        console.log(`文件读取成功，内容长度: ${content.length} 字符`);
                        console.log('文件前100个字符:', content.substring(0, 100));

                        // 测试分词器
                        const tokenizer = new DBCTokenizer(content);
                        console.log('分词器创建成功');
                        
                        const tokens = tokenizer.tokenize();
                        console.log(`分词完成，共 ${tokens.length} 个标记`);
                        console.log('前10个标记:', tokens.slice(0, 10));

                        // 测试解析器
                        const tokenizer2 = new DBCTokenizer(content);
                        const parser = new DBCParser(tokenizer2);
                        console.log('解析器创建成功');

                        const database = parser.parse();
                        console.log('解析完成');

                        const stats = database.getStatistics();
                        console.log('解析统计:', stats);

                        showResult(`✅ DBC文件解析成功！<br>
                            文件: ${file.name}<br>
                            帧数: ${stats.frameCount}<br>
                            信号数: ${stats.signalCount}<br>
                            节点数: ${stats.nodeCount}<br>
                            ${database.warnings.length > 0 ? `⚠️ 警告: ${database.warnings.length} 个` : '✅ 无警告'}`);

                    } catch (error) {
                        console.error('解析错误:', error);
                        showResult('❌ DBC文件解析失败: ' + error.message, true);
                    }
                };

                reader.onerror = function() {
                    console.error('文件读取失败');
                    showResult('❌ 文件读取失败', true);
                };

                reader.readAsText(file, 'utf-8');

            } catch (error) {
                console.error('初始化错误:', error);
                showResult('❌ 初始化失败: ' + error.message, true);
            }
        });

        // 拖拽功能
        const uploadArea = document.getElementById('uploadArea');
        
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            uploadArea.addEventListener(eventName, preventDefaults, false);
        });

        ['dragenter', 'dragover'].forEach(eventName => {
            uploadArea.addEventListener(eventName, highlight, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            uploadArea.addEventListener(eventName, unhighlight, false);
        });

        uploadArea.addEventListener('drop', handleDrop, false);

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        function highlight() {
            uploadArea.classList.add('drag-over');
        }

        function unhighlight() {
            uploadArea.classList.remove('drag-over');
        }

        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            
            if (files.length > 0) {
                document.getElementById('dbcFile').files = files;
                document.getElementById('dbcFile').dispatchEvent(new Event('change'));
            }
        }

        // 页面加载完成后的初始检查
        window.onload = function() {
            console.log('页面加载完成，开始检查环境...');
            
            // 检查script.js是否加载
            const scripts = Array.from(document.scripts);
            const hasScript = scripts.some(script => script.src.includes('script.js'));
            
            if (!hasScript) {
                console.warn('未找到script.js引用');
            } else {
                console.log('找到script.js引用');
            }

            // 检查必要的类
            const requiredClasses = ['DBCTokenizer', 'DBCParser', 'CANDatabase', 'CANFrame', 'CANSignal', 'DBCEditor'];
            requiredClasses.forEach(className => {
                if (typeof window[className] !== 'undefined') {
                    console.log(`✅ ${className} 类可用`);
                } else {
                    console.error(`❌ ${className} 类未定义`);
                }
            });
            
            console.log('环境检查完成');
        };
    </script>
    
    <!-- 加载主脚本文件 -->
    <script src="script.js"></script>
</body>
</html> 